package com.liuyk.commonlib.network;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import androidx.core.app.NotificationCompat;

import com.liuyk.commonlib.R;
import com.liuyk.commonlib.update.DownBroadcastReceiver;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 通知栏进度
 * <p>
 * Created by liuyakui on 2020-02-14.
 */
public class DownloadNotifyManager {
    private static final String CHANNEL_ID = "001";
    private static final int PROGRESS_ID = 1001;
    private static DownloadNotifyManager INSTANCE;
    private NotificationManager notificationManager;
    private Notification notification; //下载通知进度提示
    private NotificationCompat.Builder builder;

    //下载文件名
    private String mFileName;
    //下载链接
    private String mDownloadUrl;
    private final ConcurrentHashMap<String, DownloadInfo> mDownloadInfoMap;

    private DownloadNotifyManager(Context context) {
        initNotification(context);
        mDownloadInfoMap = new ConcurrentHashMap<>();
    }

    public synchronized static DownloadNotifyManager getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = new DownloadNotifyManager(context);
        }
        return INSTANCE;
    }

    //初始化通知
    private void initNotification(Context context) {
        try {
            notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            builder = new NotificationCompat.Builder(context, CHANNEL_ID);
            builder.setContentTitle("正在下载...") //设置通知标题
                    .setSmallIcon(R.mipmap.update_apk_icon)
                    .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.update_apk_icon)) //设置通知的大图标
                    .setDefaults(Notification.DEFAULT_LIGHTS) //设置通知的提醒方式： 呼吸灯
                    .setPriority(NotificationCompat.PRIORITY_MAX) //设置通知的优先级：最大
                    .setOnlyAlertOnce(true)
                    .setSound(null)
                    .setVibrate(new long[]{0})//关闭震动
                    .setAutoCancel(false)//设置通知被点击一次是否自动取消
                    .setContentText("下载总进度:" + "0%")
                    .setProgress(100, 0, false);

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "download_channel001", NotificationManager.IMPORTANCE_DEFAULT);
                notificationManager.createNotificationChannel(channel);
                builder.setChannelId(CHANNEL_ID);
            }

            notification = builder.build();//构建通知对象
            notification.flags = Notification.FLAG_NO_CLEAR;//不可以清楚
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void show() {
        try {
            notification = builder.build();
            notificationManager.notify(PROGRESS_ID, notification);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void notifyChanger() {
        try {
            notification = builder.build();
            notificationManager.notify(PROGRESS_ID, notification);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //icon title如果不设置，会用默认的，如果需要设置，必须在notify之前设置
    public void setContentTitle(String title) {
        builder.setContentTitle(title);
    }

    public void setSmallIcon(int resId) {
        builder.setSmallIcon(resId);
    }

    public void setLargeIcon(Bitmap bitmap) {
        builder.setLargeIcon(bitmap);
    }

    public void updateProgress(String downloadUrl, String fileName, long length, long progress) {
        mFileName = fileName;
        mDownloadUrl = downloadUrl;
        try {
            DownloadInfo downloadInfo = mDownloadInfoMap.get(downloadUrl);
            if (downloadInfo == null) {
                downloadInfo = new DownloadInfo();
                mDownloadInfoMap.put(downloadUrl, downloadInfo);
            }
            downloadInfo.downloadName = fileName;
            downloadInfo.l = length;
            downloadInfo.progress = progress;
            downloadInfo.url = downloadUrl;

            long sumLength = 0;
            long sumProgress = 0;
            Set<String> strings = mDownloadInfoMap.keySet();
            for (String key : strings) {
                DownloadInfo di = mDownloadInfoMap.get(key);
                sumLength = sumLength + di.l;
                sumProgress = sumProgress + di.progress;
            }

            builder.setProgress((int) sumLength, (int) sumProgress, false);
            if (sumLength <= 0) {
                sumLength = 100;
            }
            float percent = (sumProgress * 1.0f / sumLength * 1.0f * 100f);
            builder.setContentText((int) percent + "%");
            builder.setContentTitle(mDownloadInfoMap.size() + "个文件正在下载: ");
            notifyChanger();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //在一些特定情况下，更新通知栏内容，例如：下载失败
    public void updateNotify(String downloadUrl, String fileName, String msg) {
        mFileName = fileName;
        mDownloadUrl = downloadUrl;
        try {
            builder.setContentText(msg);
            notifyChanger();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void clickRetry(Context context) {
        Intent intentClick = new Intent(context, DownBroadcastReceiver.class);
        intentClick.setAction(DownBroadcastReceiver.RETRY_ACTION);
        intentClick.putExtra("versionName", mFileName);
        intentClick.putExtra("apkUrl", mDownloadUrl);
        PendingIntent pendingIntentClick = PendingIntent.getBroadcast(
                context, 0, intentClick, PendingIntent.FLAG_ONE_SHOT);
        builder.setContentIntent(pendingIntentClick);
        notification = builder.build();
        notificationManager.notify(PROGRESS_ID, notification);
    }

    public void cancel() {
        try {
            notificationManager.cancel(PROGRESS_ID);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
